package com.stars.easyms.schedule.factory;

import com.stars.easyms.schedule.util.ApplicationContextHolder;
import com.stars.easyms.schedule.util.DistributedSchedulePackageUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 分布式调度的SqlSession工厂类
 *
 * @author guoguifang
 */
public class DbScheduleSqlSessionFactory {

    private static final Logger logger = LoggerFactory.getLogger(DbScheduleSqlSessionFactory.class);

    private static SqlSessionFactory dbScheduleSqlSessionFactory;

    public static SqlSessionFactory getSqlSessionFactory() {
        if (dbScheduleSqlSessionFactory == null) {
            synchronized (DbScheduleSqlSessionFactory.class) {
                if (dbScheduleSqlSessionFactory == null) {
                    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
                    try {
                        //指定数据源(这个必须有，否则报错)
                        sqlSessionFactoryBean.setDataSource(ApplicationContextHolder.getApplicationContext().getBean(DataSource.class));
                        //指定基包
                        sqlSessionFactoryBean.setTypeAliasesPackage(DistributedSchedulePackageUtil.getRepositoryPackageName());
                        List<Resource> resourceList = new ArrayList<>();
                        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:" + DistributedSchedulePackageUtil.getRepositoryPackageName().replace(".", "/") + "/*Mapper.xml");
                        resourceList.addAll(Arrays.asList(resources));
                        //指定xml文件位置
                        sqlSessionFactoryBean.setMapperLocations(resourceList.toArray(new Resource[resourceList.size()]));
                        dbScheduleSqlSessionFactory = sqlSessionFactoryBean.getObject();
                    } catch (Exception e) {
                        logger.error("Create distributed schedule 'SqlSessionFactory' failure!", e);
                        System.exit(1);
                    }
                }
            }
        }
        return dbScheduleSqlSessionFactory;
    }
}
